<template>
  <div>
    <el-form-item
      label="对齐方式"
    >
      <el-select v-model="activeData.table.align" placeholder="请选择">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
    </el-form-item>
    <div v-if="activeData.table.rows">
      <el-divider>行</el-divider>
      <draggable
        :animation="340"
        :list="activeData.table.rows"
        group="selectItem"
        handle=".option-drag"
      >
        <div
          v-for="(item, index) in activeData.table.rows"
          :key="index"
          class="select-item"
        >
          <div class="select-line-icon option-drag">
            <i class="el-icon-s-operation" />
          </div>
          <el-input
            v-model="item.label"
            placeholder="选项名"
            size="small"
          />
          <div
            class="close-btn select-line-icon"
            @click="activeData.table.rows.splice(index, 1)"
          >
            <i class="el-icon-remove-outline" />
          </div>
        </div>
      </draggable>
      <div style="margin-left: 20px;margin-bottom: 10px">
        <el-button
          icon="el-icon-circle-plus-outline"
          style="padding-bottom: 0"
          type="text"
          @click="addSelectItem(activeData.table.rows)"
        >
          添加行标题
        </el-button>
        <el-button
          icon="el-icon-document-copy"
          style="padding-bottom: 0"
          type="text"
          @click="openBatchEditDialogHandle('rows')"
        >
          批量编辑行标题
        </el-button>
      </div>
    </div>
    <div v-if="activeData.table.columns">
      <el-divider>列</el-divider>
      <draggable
        :animation="340"
        :list="activeData.table.columns"
        group="selectItem"
        handle=".option-drag"
      >
        <div
          v-for="(item, index) in activeData.table.columns"
          :key="index"
          class="select-item"
        >
          <div class="select-line-icon option-drag">
            <i class="el-icon-s-operation" />
          </div>
          <el-input
            v-model="item.label"
            placeholder="选项名"
            size="small"
          />
          <!-- 删除 -->
          <div
            class="close-btn select-line-icon"
            @click="activeData.table.columns.splice(index, 1)"
          >
            <i class="el-icon-remove-outline" />
          </div>
          <!-- 编辑 -->
          <div
            class="close-btn select-line-icon"
            @click="handleColumnItem(activeData.table.columns,index)"
          >
            <i class="el-icon-edit"></i>
          </div>
        </div>
      </draggable>
      <div style="margin-left: 20px;margin-bottom: 10px">
        <el-button
          icon="el-icon-circle-plus-outline"
          style="padding-bottom: 0"
          type="text"
          @click="addSelectItem(activeData.table.columns,2)"
        >
          添加选项
        </el-button>
        <el-button
          icon="el-icon-document-copy"
          style="padding-bottom: 0"
          type="text"
          @click="openBatchEditDialogHandle('columns')"
        >
          批量编辑列标题
        </el-button>
      </div>
    </div>
    <!-- 批量编辑 -->
    <el-dialog
      title="批量编辑"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <span class="desc-text">每行对应一个选项</span>
      <el-input v-model="batchItemValue" type="textarea" :autosize="{ minRows: 20, maxRows: 5000}"
                placeholder="选项1 选项2  选项3 "
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="batchEditSelectItems">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑列 -->
    <el-dialog
      title="编辑"
      center
      :visible.sync="editColumnVisible"
      width="30%"
      @close="closeDialog('ruleForm')"
    >
      <el-form :model="columnForm" :label-width="formLabelWidth" ref="ruleForm">
        <el-form-item label="列标题：">
          <el-input v-model="columnForm.label" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="列类型：">
            <span @click="selectType(item,index)" v-for="(item,index) in typeOption" :key="'option'+index">
              <img :src="require('../../../assets/images/'+item.icon+'.png')" :class="['typeIcon',item.checked ? 'checkedIcon' : '']"/>
          </span>
        </el-form-item>
        <div v-if="columnForm.type == 1">
          <el-form-item label="是否多选：" >
              <el-switch
                v-model="columnForm.multipleSelect"
                active-color="#1890ff"
                inactive-color="#ccc">
              </el-switch>
          </el-form-item>
          <el-form-item label="选项设置：">
            <div><i class="el-icon-circle-plus-outline" @click="addOption()"></i></div>
            <div>
              <!-- <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm"> -->
                <div v-for="(item,index) in columnForm.options" :key="index" class="options">
                    <el-form-item label=""
                        :prop="'options.' + index + '.label'"
                        :rules="itemRules">
                        <el-input  v-model.trim="item.label" autocomplete="off" style="width:100px;"></el-input>
                        <i class="el-icon-remove-outline" style="margin-left:5px;display: inline-block;" @click="columnForm.options.splice(index,1)"></i>
                    </el-form-item>
                </div>
              <!-- </el-form> -->
              
            </div>
          </el-form-item>
          <div v-if="columnForm.multipleSelect">
            <el-form-item>
              <span slot="label">
                至少应选：
                <el-tooltip
                  class="item"
                  content="至少应选需要和最多可选一起使用，并且小于最多可选，否则将导致多选无法选中"
                  effect="dark"
                  placement="top-start"
                >
                  <i class="el-icon-warning" />
                </el-tooltip>
              </span>
              <el-input-number
                :min="0"
                @change="handleMax()"
                v-model="columnForm.min"
                placeholder="至少应选"
                :max="columnForm.options.length"
              />
            </el-form-item>
            <el-form-item label="最多可选：">
              <el-input-number
                :min="columnForm.min"
                v-model="columnForm.max"
                placeholder="最多可选"
                :max="columnForm.options.length"
              />
            </el-form-item>
            <el-form-item>
              <span slot="label">
                多选互斥：
                <el-tooltip
                  class="item"
                  content="设置多选互斥后，将不可以选择其他选项。例如选择「以上都不是」。"
                  effect="dark"
                  placement="top-start"
                >
                  <i class="el-icon-warning" />
                </el-tooltip>
              </span>
              <el-switch v-model="columnForm.withExclusiveChoice" />
            </el-form-item>
            <el-form-item
              class="exclusive-choice-api-codes"
              v-if="columnForm.withExclusiveChoice"
            >
              <el-select
                v-model="columnForm.multipleOption"
                multiple
                placeholder="请选择"
              >
                <el-option
                  v-for="item in columnForm.options"
                  :key="item.value"
                  :label="item.label"
                  :value="item"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </div>
          
        </div>
        <!-- 填空和问答 -->
        <el-form-item label="验证设置：" v-if="columnForm.type == 2 || columnForm.type == 3">
          <el-select v-model="columnForm.testType" placeholder="请选择">
              <el-option
                v-for="item in testOption"
                :key="item.label"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
        </el-form-item>
        <div v-if="columnForm.type == 4">
          <el-form-item label="文件类型：">
            <el-select
              v-model="columnForm.fileType"
              :style="{ width: '100%' }"
              clearable
              allow-create
              collapse-tags
              placeholder="请选择文件类型"
            >
              <el-option label="图片" value="image/*" />
              <el-option label="视频" value="video/*" />
              <el-option label="音频" value="audio/*" />
              <el-option label="excel" value=".xls,.xlsx" />
              <el-option label="word" value=".doc,.docx" />
              <el-option label="pdf" value=".pdf" />
              <el-option label="txt" value=".txt" />
              <el-option label="ppt" value=".ppt,.pptx" />
            </el-select>
          </el-form-item>
          <el-form-item label="文件大小：">
            <el-input
              v-model.number="columnForm.fileSize"
              placeholder="请输入文件大小"
            >
              <el-select
                slot="append"
                v-model="columnForm.fileUnit"
                :style="{ width: '66px' }"
              >
                <el-option label="KB" value="KB" />
                <el-option label="MB" value="MB" />
                <el-option label="GB" value="GB" />
              </el-select>
            </el-input>
          </el-form-item>
          <el-form-item label="多选文件：">
              <el-switch
                v-model="columnForm.multipleFile"
                active-color="#1890ff"
                inactive-color="#ccc">
              </el-switch>
          </el-form-item>
          <el-form-item label="文件个数：" v-if="columnForm.multipleFile">
            <el-input-number :min="0" v-model="columnForm.fileNum"  label="描述文字"></el-input-number>
          </el-form-item>
        </div>
        <el-form-item label="是否必填：">
              <el-switch
                v-model="columnForm.required"
                active-color="#1890ff"
                inactive-color="#ccc">
              </el-switch>
          </el-form-item>
        <el-form-item label="列宽设置：">
          宽 <el-input v-model="columnForm.width" autocomplete="off" style="width:100px;"></el-input> px
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editColumnVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitItems">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import draggable from 'vuedraggable'
import _ from 'lodash'
import { parse } from '../../../lib/formulajs/utils/criteria-eval'

export default {
  name: 'MatrixOption',
  components: {
    draggable
  },
  props: ['activeData'],
  data() {
    let handleDuplicate = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入选项"))
      } else {
        var newArr = this.columnForm.options.filter((item2,index2) => {
            return item2.label == value
        })
        if(newArr.length-1){
          callback(new Error("不能重名"))
        }else{
          callback()
        }
      }
    }
    return {
      options:[
        {
          label:'居中',
          value:'center'
        },
        {
          label:'居左',
          value:'left'
        },
        {
          label:'居右',
          value:'right'
        }
      ],
      batchItemValue: '',
      batchDataKey: '',
      dialogVisible: false,
      editColumnVisible:false,
      testOption:[
        {
          label:'无',
          value:1
        },{
          label:'阿拉伯数字',
          value:2
        },{
          label:'固定电话',
          value:3
        },{
          label:'手机号',
          value:4
        },{
          label:'邮政编码',
          value:5
        },{
          label:'Email',
          value:6
        },{
          label:'URL',
          value:7
        },{
          label:'身份证',
          value:8
        },{
          label:'日期',
          value:9
        },{
          label:'中文',
          value:10
        },{
          label:'中英文',
          value:11
        }],
      typeOption:[
          {
            icon:'el-icon-1',
            value:1,
            checked:true
          },
          {
            icon:'el-icon-2',
            value:2,
            checked:false
          },
          {
            icon:'el-icon-3',
            value:3,
            checked:false
          },
          {
            icon:'el-icon-4',
            value:4,
            checked:false
          }
        ],
        min:1,
      columnForm:{
        label:'',//标题
        type:1,//类型
        multipleSelect:false,
        options:[],//选项设置
        min:0,//至少应选
        max:0,//至多应选
        withExclusiveChoice:false,//多选互斥
        multipleOption:[],//多选互斥选项
        fileType:'',//文件类型
        fileSize:'',//文件大小
        fileUnit:'MB',//文件单位
        multipleFile:false,//是否多选文件
        fileNum:0,//文件个数
        testType:'',//验证设置
        width:130,
        required:true
      },
      formLabelWidth:'100px',
      selectedColumn:{},
      selectedIndex:0,
      itemRules:[
        {max:40,trigger:'blur',validator:handleDuplicate}
      ]
    }
  },
  methods: {
    handleMax(){
      if(this.columnForm.max<this.columnForm.min){
        this.columnForm.max = this.columnForm.min
      }
    },
    selectType(item,index){
      this.columnForm.type=item.value
      item.checked = true
      this.typeOption.forEach((item2,index2) =>{
        if(index != index2){
          item2.checked=false
        }
      })
    },
    // 编辑列保存
    submitItems(){
      this.activeData.table.columns[this.selectedIndex].columnForm=JSON.parse(JSON.stringify({...this.columnForm}))
      this.activeData.table.columns[this.selectedIndex].label=this.columnForm.label
      this.editColumnVisible = false
    },
    addOption(){
      const lastItem = _.last(this.columnForm.options) || {value: 0}
      const value = lastItem.value !== 0 ? _.max(_.values(this.columnForm.options.map(item => item.value))) + 1 : lastItem.value + 1
      this.columnForm.options.push({
        label: '',
        value: lastItem ? value : 1,
        // disabled:false
      })
    },
    handleColumnItem(column,index){
      this.$nextTick(() => {
          this.selectedColumn = column[index]
          this.selectedIndex = index;
          this.columnForm={...column[index].columnForm}
          this.columnForm.label=column[index].label
          this.typeOption.forEach((item2,index2) =>{
            if(this.columnForm.type == item2.value){
              item2.checked=true
            }else{
              item2.checked=false
            }
          })
          this.editColumnVisible=true
        })
    },
    addSelectItem(data,flag) {
      if(flag){
        data.push({
          id: new Date().getTime(),
          label: '',
          columnForm:{
            label:'',//标题
            type:1,//类型
            multipleSelect:false,
            options:[],//选项设置
            min:0,//至少应选
            max:0,//至多应选
            withExclusiveChoice:false,//多选互斥
            multipleOption:[],//多选互斥选项
            fileType:'',//文件类型
            fileSize:'',//文件大小
            fileUnit:'MB',//文件单位
            multipleFile:false,//是否多选文件
            fileNum:0,//文件个数
            testType:'',//验证设置
            width:130,
            required:true
          }
        })
      }else{
        data.push({
          id: new Date().getTime(),
          label: ''
        })
      }
    },
    closeDialog(ruleForm){
      this.columnForm={
            label:'',//标题
            type:1,//类型
            options:[],//选项设置
            min:0,//至少应选
            max:0,//至多应选
            withExclusiveChoice:false,//多选互斥
            multipleOption:[],//多选互斥选项
            fileType:'',//文件类型
            fileSize:'',//文件大小
            fileUnit:'MB',//文件单位
            multipleFile:false,//是否多选文件
            fileNum:0,//文件个数
            testType:'',//验证设置
            width:130,
            required:true
          }
      this.$refs[ruleForm].resetFields();
    },
    openBatchEditDialogHandle(key) {
      this.batchDataKey = key
      let data = this.activeData.table[key]
      this.batchItemValue = _.join(data.map(item => item.label), '\n')
      this.dialogVisible = true
    },
    async batchEditSelectItems() {
      
      const arrStrs = this.batchItemValue
      const arr = arrStrs.split('\n')
      // 获取原来的下标 避免导致id变化
      let oldData = this.activeData.table[this.batchDataKey]
      let labels = oldData.map(item => item.label)
      if (arr.length > 0) {
        const options = []
        for (let index = 0; index < arr.length; index++) {
          const element = arr[index]
          if (element.length > 0) {
            let oIndex = labels.indexOf(element)
            if(this.batchDataKey == 'columns'){
              var tempColumnForm = {
                  label:'',//标题
                  type:1,//类型
                  multipleSelect:false,
                  options:[],//选项设置
                  min:0,//至少应选
                  max:0,//至多应选
                  withExclusiveChoice:false,//多选互斥
                  multipleOption:[],//多选互斥选项
                  fileType:'',//文件类型
                  fileSize:'',//文件大小
                  fileUnit:'MB',//文件单位
                  multipleFile:false,//是否多选文件
                  fileNum:0,//文件个数
                  testType:'',//验证设置
                  width:130,
                  required:true
                }
              options.push({
                id: new Date().getTime()+index,
                // id: oIndex > -1 ? oldData[oIndex].id : new Date().getTime()+index,
                label: element,
                columnForm:oIndex > -1 ? oldData[oIndex].columnForm : tempColumnForm
              })
            }else{
              options.push({
                id: new Date().getTime()+index,
                // id: oIndex > -1 ? oldData[oIndex].id : new Date().getTime()+index,
                label: element
              })
            }
            
          }
        }
        this.$set(this.activeData.table, this.batchDataKey, options)
        this.dialogVisible = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.select-item {
  display: flex;
  border: 1px dashed #fff;
  box-sizing: border-box;
  align-items: center;

  & .close-btn {
    cursor: pointer;
    color: #f56c6c;
  }

  & .el-input + .el-input {
    margin-left: 4px;
  }
}

.select-item + .select-item {
  margin-top: 4px;
}

.select-item.sortable-chosen {
  border: 1px dashed #409eff;
}

.select-line-icon {
  line-height: 32px;
  font-size: 22px;
  padding: 0 4px;
  color: #777;
}
.el-icon-edit{
  color:#1890ff
}
.option-drag {
  cursor: move;
}
.options{
  margin-bottom: 5px;
}
.typeIcon{
  width:18px;
  height:18px;
  display: inline-block;
  margin-right:10px;
}
.checkedIcon{
  border:2px solid #f80;
}
.el-dialog__header{
  background-color:#385DC7 !important;
  text-align: center;
}
.el-dialog__title,.el-dialog__headerbtn i{
  color: #fff !important;
}
.el-icon-circle-plus-outline{
  color:#0B5FD5;
  font-size:19px;
  font-weight: bold;
}
.el-icon-remove-outline{
  color:#FA5151;
  font-size:19px;
  font-weight: bold;
}
</style>
